<template>
    <div>
        <div  class="text-[80px] font-bold">
            你好，我是泽鑫
        </div>
        <div class="text-[60px]">
            {{ temp }}
            <span class="cursor">|</span>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import gsap from 'gsap/src'
let textList = ref(["写代码的每一天", "都是在搭建自己的宇宙"])
let textIndex = 0
let originalText = textList.value[0]
let temp = ref(textList.value[0])
let cursor: any
let timer: any = null;

const change = (state:boolean) => {
    clearInterval(timer)
    //开始动画
    if (state) {
        timer = setInterval(() => {
            if (temp.value.length === 0) {
                clearInterval(timer)
                cursor.resume() //光标继续闪烁
                //循环文字数组
                textIndex++
                if (textIndex == textList.value.length)
                    textIndex = 0
                originalText = textList.value[textIndex]
                //延迟一秒逐步恢复文字
                setTimeout(async () => {
                    for (let i = 0; i < originalText.length; i++) {
                        temp.value = originalText.slice(0, i + 1)
                        await new Promise(resolve => setTimeout(resolve, 300))
                    }
                    await new Promise(resolve => setTimeout(resolve, 1000))
                    change(true)
                }, 1000)
            }
            else {
                temp.value = temp.value.slice(0, temp.value.length - 1)
                cursor.pause(0)
            }
        }, 300);
    }
    //初始化
    else {
        originalText = textList.value[0]
        temp.value = originalText
        cursor.restart()
    }
}

onMounted(async () => {
    cursor = gsap.to(".cursor", {
        opacity: 0,
        repeat: -1,
        yoyo: true,
        duration: 0.65
    }).play()
})

defineExpose({ change })
</script>
<style scoped></style>